//
//  BarberTimeView.m
//  HeadYang
//
//  Created by sunmingming on 15/7/19.
//  Copyright (c) 2015年 xiaoluoli. All rights reserved.
//

#import "BarberTimeView.h"

@interface BarberTimeView()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong) UITableView *mainTableView;
@property(nonatomic,weak) UILabel *dayLabel;
@property(nonatomic,weak) UIButton *yyBut;
@property(nonatomic,strong) NSDictionary *barberDetailDic;
@property(nonatomic,strong) NSDictionary *barberServiceDic;
@property(nonatomic,strong) NSMutableArray *barberTimeArray;

@end

@implementation BarberTimeView

@synthesize barberTimeArray = _barberTimeArray;

- (instancetype)initWithDetailDic:(NSDictionary*)aDic
                    andServiceDic:(NSDictionary*)bDic{
    //solid frame,up validition is a just frame...
    CGRect solidRect = CGRectMake(0,0,kDeviceWidth,kDeviceWidth);
    if(!(self = [super initWithFrame:solidRect])){
        return nil;
    }
    self.barberTimeArray = [NSMutableArray array];
    APPALL.startTimeFlag = 0;
    self.barberDetailDic = aDic;
    self.barberServiceDic = bDic;
    self.selectDate = [NSDate date];
    self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceWidth) style:UITableViewStylePlain];
    self.mainTableView.dataSource = self;
    self.mainTableView.delegate = self;
    self.mainTableView.backgroundColor = [UIColor blackColor];
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addSubview:self.mainTableView];
    
    [self fecthIdleTIme];
    
    return self;
}

-(void)fecthIdleTIme{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [dateFormatter stringFromDate:APPALL.selectDate];
//    date - 查询日期，格式为"yyyy-MM-dd"，必填。
    NSDictionary *para =
    @{@"barber":[APPALL.barberDetailDic valueForKey:@"id"],
      @"date":dateStr,
      @"service":[NSString stringWithFormat:@"%i",APPALL.myType],
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"order_timeSheet" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                }
                    break;
                case 1:
                {
                    [self.barberTimeArray removeAllObjects];
                    NSArray *cityArray = [aSucData objectForKey:@"idle"];
                    for (NSDictionary *dic in cityArray) {
                        [_barberTimeArray addObject:dic];
                    }
                    [self.mainTableView reloadData];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
            return 100.0f;
        case 1:
            return 40.0f;
        case 2:
            return 180.0f;
        default:
            break;
    }
    return 0.0f;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *inde;
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:{
                    inde = @"barberpoptopid";
                    cell = [tableView dequeueReusableCellWithIdentifier:inde];
                    if (cell == nil) {
                        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"BarberPopTop" owner:self options:nil];
                        cell = [nib objectAtIndex:0];
                    }
                    UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
                    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
                    if(!self.yyBut){
                        self.yyBut = (UIButton*)[cell viewWithTag:3];
                        [self.yyBut addTarget:self action:@selector(yyPressed:) forControlEvents:UIControlEventTouchUpInside];
                    }
                    NSCalendar*calendar = [NSCalendar currentCalendar];
                    NSDateComponents*comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)
                                       fromDate:self.selectDate];
                    NSInteger year = [comps year];
                    NSInteger month = [comps month];
                    NSInteger day = [comps day];
                    lab1.text = [NSString stringWithFormat:@"%02d",day];
                    lab2.text = [NSString stringWithFormat:@"%04d年%02d月",year,month];
                }
                    break;
                case 1:{
                    inde = @"BarberPopMidID";
                    cell = [tableView dequeueReusableCellWithIdentifier:inde];
                    if (cell == nil) {
                        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"BarberPopMid" owner:self options:nil];
                        cell = [nib objectAtIndex:0];
                    }
                    NSDateComponents*comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:self.selectDate];
                    NSInteger day = [comps day];
                    NSString *dayStr = [NSString stringWithFormat:@"%02d",day];
                    UIButton *but1 = (UIButton*)[cell viewWithTag:1];
                    UIButton *but2 = (UIButton*)[cell viewWithTag:2];
                    UIButton *but3 = (UIButton*)[cell viewWithTag:3];
                    UIButton *but4 = (UIButton*)[cell viewWithTag:4];
                    UIButton *but5 = (UIButton*)[cell viewWithTag:5];
                    UIButton *but6 = (UIButton*)[cell viewWithTag:6];
                    UIButton *but7 = (UIButton*)[cell viewWithTag:7];
                    {
                        NSString *butStr = [self dateAfterDay:0];
                        [but1 setTitle:butStr
                              forState:UIControlStateNormal];
                        [but1 addTarget:self action:@selector(datePressed:) forControlEvents:UIControlEventTouchUpInside];
                        [but1 setTitleColor:([dayStr isEqualToString:butStr]?[UIColor redColor]:[UIColor blackColor]) forState:UIControlStateNormal];
                    }
                    {
                        NSString *butStr = [self dateAfterDay:1];
                        [but2 setTitle:butStr
                              forState:UIControlStateNormal];
                        [but2 addTarget:self action:@selector(datePressed:) forControlEvents:UIControlEventTouchUpInside];
                        [but2 setTitleColor:([dayStr isEqualToString:butStr]?[UIColor redColor]:[UIColor blackColor]) forState:UIControlStateNormal];
                    }
                    {
                        NSString *butStr = [self dateAfterDay:2];
                        [but3 setTitle:butStr
                              forState:UIControlStateNormal];
                        [but3 addTarget:self action:@selector(datePressed:) forControlEvents:UIControlEventTouchUpInside];
                        [but3 setTitleColor:([dayStr isEqualToString:butStr]?[UIColor redColor]:[UIColor blackColor]) forState:UIControlStateNormal];
                    }
                    {
                        NSString *butStr = [self dateAfterDay:3];
                        [but4 setTitle:butStr
                              forState:UIControlStateNormal];
                        [but4 addTarget:self action:@selector(datePressed:) forControlEvents:UIControlEventTouchUpInside];
                        [but4 setTitleColor:([dayStr isEqualToString:butStr]?[UIColor redColor]:[UIColor blackColor]) forState:UIControlStateNormal];
                    }
                    {
                        NSString *butStr = [self dateAfterDay:4];
                        [but5 setTitle:butStr
                              forState:UIControlStateNormal];
                        [but5 addTarget:self action:@selector(datePressed:) forControlEvents:UIControlEventTouchUpInside];
                        [but5 setTitleColor:([dayStr isEqualToString:butStr]?[UIColor redColor]:[UIColor blackColor]) forState:UIControlStateNormal];
                    }
                    {
                        NSString *butStr = [self dateAfterDay:5];
                        [but6 setTitle:butStr
                              forState:UIControlStateNormal];
                        [but6 addTarget:self action:@selector(datePressed:) forControlEvents:UIControlEventTouchUpInside];
                        [but6 setTitleColor:([dayStr isEqualToString:butStr]?[UIColor redColor]:[UIColor blackColor]) forState:UIControlStateNormal];
                    }
                    {
                        NSString *butStr = [self dateAfterDay:6];
                        [but7 setTitle:butStr
                              forState:UIControlStateNormal];
                        [but7 addTarget:self action:@selector(datePressed:) forControlEvents:UIControlEventTouchUpInside];
                        [but7 setTitleColor:([dayStr isEqualToString:butStr]?[UIColor redColor]:[UIColor blackColor]) forState:UIControlStateNormal];
                    }
                }
                    break;
                case 2:{
                    inde = @"BarberTopDownID";
                    cell = [tableView dequeueReusableCellWithIdentifier:inde];
                    if (cell == nil) {
                        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"BarberPopDown" owner:self options:nil];
                        cell = [nib objectAtIndex:0];
                    }
                    NSArray *butArray = @[
                    (UIButton*)[cell viewWithTag:9],
                    (UIButton*)[cell viewWithTag:10],
                    (UIButton*)[cell viewWithTag:11],
                    (UIButton*)[cell viewWithTag:12],
                    (UIButton*)[cell viewWithTag:13],
                    (UIButton*)[cell viewWithTag:14],
                    (UIButton*)[cell viewWithTag:15],
                    (UIButton*)[cell viewWithTag:16],
                    (UIButton*)[cell viewWithTag:17],
                    (UIButton*)[cell viewWithTag:18],
                    (UIButton*)[cell viewWithTag:19],
                    (UIButton*)[cell viewWithTag:20]
                    ];
                    NSDateComponents*comps = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:self.selectDate];
                    NSInteger weekday = [comps weekday]; // 星期几（注意，周日是“1”，周一是“2”。。。。）
                    NSString *restStr = [self.barberDetailDic valueForKey:@"restDayByWeek"];
                    if([restStr containsString:[NSString stringWithFormat:@"%i",weekday]]){
                        for(UIButton *but in butArray){
                            [self setButton:but andAvail:NO];
                        }
                    }else{
                        NSMutableString *str = [NSMutableString string];
                        for(NSDictionary *timeDic in self.barberTimeArray){
                            [str appendFormat:@",%i",[[timeDic valueForKey:@"timePiece"] integerValue]];
                        }
                        for(UIButton *but in butArray){
                            BOOL isAvail = NO;
                            int baseTag = [but tag] * 4 + 1;
                            if([str containsString:[NSString stringWithFormat:@"%02i",baseTag]]){
                                isAvail = YES;
                            }
                            [but addTarget:self action:@selector(timePressed:) forControlEvents:UIControlEventTouchUpInside];
                            [self setButton:but andAvail:isAvail];
                        }
                    }
                }
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }
    return cell;
}

-(void)datePressed:(id)sender{
    UIButton *pressedBut = (UIButton*)sender;
    APPALL.startTimeFlag = 0;
    self.selectDate = [NSDate dateWithTimeIntervalSinceNow:([pressedBut tag] - 1) * 24 * 60 * 60];
    APPALL.selectDate = self.selectDate;
    [self fecthIdleTIme];
}

-(void)timePressed:(id)sender{
    UIButton *pressedBut = (UIButton*)sender;
    if(![[pressedBut titleForState:UIControlStateNormal] containsString:@"不"]){
        APPALL.startTimeFlag = [pressedBut tag] * 4 + 1;
        for(NSDictionary *timeDic in self.barberTimeArray){
            if([[timeDic valueForKey:@"timePiece"] integerValue] == APPALL.startTimeFlag){
                APPALL.servicePrice = [[timeDic valueForKey:@"price"] floatValue];
                break;
            }
        }
        [self.mainTableView reloadData];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section != 1)
        return;
}

-(NSString*)dateAfterDay:(NSInteger)i{
    NSDate *date0 = [NSDate dateWithTimeIntervalSinceNow:i * 24 * 60 * 60];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents*comps =
    [calendar components:NSDayCalendarUnit
                fromDate:date0];
    NSInteger day = [comps day];
    return [NSString stringWithFormat:@"%02d",day];
}

-(void)setButton:(UIButton*)aBut andAvail:(BOOL)aAvai{
    NSString *priceStr = @"";
    if(!aAvai){
        [aBut setTitle:[NSString stringWithFormat:@"%02i:00\n不可预约",[aBut tag]]
              forState:UIControlStateNormal];
        [aBut setTitleColor:[UIColor blackColor]
                   forState:UIControlStateNormal];
        [aBut setBackgroundColor:[UIColor whiteColor]];
    }
    if(aAvai){
        for(NSDictionary *timeDic in self.barberTimeArray){
            if([[timeDic valueForKey:@"timePiece"] integerValue] == [aBut tag] * 4 + 1){
                priceStr = [NSString stringWithFormat:@"\n%.2f元",[[timeDic valueForKey:@"price"] floatValue]];
                break;
            }
        }
        [aBut setTitle:[NSString stringWithFormat:@"%02i:00\n可预约%@",[aBut tag],priceStr]
              forState:UIControlStateNormal];
        [aBut setTitleColor:[UIColor whiteColor]
                   forState:UIControlStateNormal];
        if(APPALL.startTimeFlag == ([aBut tag] * 4 + 1)){
            [aBut setBackgroundColor:[UIColor redColor]];
        }else{
            [aBut setBackgroundColor:[UIColor pinkColor]];
        }
    }
}

-(void)yyPressed:(id)sender{
    if(APPALL.startTimeFlag > 0){
        [self.myDelegate yyPressed:nil];
    }else{
        [SVProgressHUD showErrorWithStatus:@"请选择预约时间"];
    }
}

@end
/*
 NSDate*date = [NSDate date];
 NSCalendar*calendar = [NSCalendar currentCalendar];
 NSDateComponents*comps;
 
 // 年月日获得
 comps =[calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)
 fromDate:date];
 NSIntegeryear = [comps year];
 NSIntegermonth = [comps month];
 NSIntegerday = [comps day];
 NSLog(@"year:%d month: %d, day: %d", year, month, day);
 
 //当前的时分秒获得
 comps =[calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit)
 fromDate:date];
 NSIntegerhour = [comps hour];
 NSIntegerminute = [comps minute];
 NSIntegersecond = [comps second];
 NSLog(@"hour:%d minute: %d second: %d", hour, minute, second);
 
 // 周几和星期几获得
 comps =[calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit |NSWeekdayOrdinalCalendarUnit)
 fromDate:date];
 NSInteger week = [comps week]; // 今年的第几周
 NSIntegerweekday = [comps weekday]; // 星期几（注意，周日是“1”，周一是“2”。。。。）
 NSIntegerweekdayOrdinal = [comps weekdayOrdinal]; // 这个月的第几周
 NSLog(@"week:%d weekday: %d weekday ordinal: %d", week, weekday, weekdayOrdinal);
 
 NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
 if(dateSwitch.on)
 [dateFormattersetDateFormat:@"dd-MMM-yyy,hh:mm:ss"];
 else
 [dateFormatter setDateFormat:@"hh:mm:ss"];
 labelTime.text = [dateFormatter stringFromDate:[NSDatedate]];
 labelTime.font = [UIFontsystemFontOfSize:fontSlider.value];
 [dateFormatter release];
 */